package cn.pzx.base_module.base

import android.view.KeyEvent
import android.webkit.WebView
import android.widget.LinearLayout
import cn.pzx.base_module.databinding.ActivityBaseWebUrlBinding
import cn.pzx.base_module.vm.WebViewVm
import com.blankj.utilcode.util.LogUtils
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient

/**
 * @author pzx
 * @description:
 * @date :3/16/21 10:49 AM
 */
open class BaseWebUrlActivity : BaseActivity<WebViewVm, ActivityBaseWebUrlBinding>() {

    lateinit var mAgentWeb: AgentWeb
    override fun initView() {


        LogUtils.e(intent.getStringExtra("url"))


        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(vb.webRoot, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebChromeClient(
                MWebChromeClient(vb)
            )
            .setWebViewClient(MWebClient(vb))
//            .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
            .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
//            .setWebLayout(WebLayout(this))
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
            .interceptUnkownUrl() //拦截找不到相关页面的Scheme
            .createAgentWeb()
            .ready()
            .go(intent.getStringExtra("url"))
        initTitleBar(vb.titleBar)


    }

    override fun initClick() {
    }

    override fun initData() {


    }

    override fun initVM() {
    }

    class MWebClient @JvmOverloads constructor(var vb: ActivityBaseWebUrlBinding) :
        WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
        }

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    class MWebChromeClient @JvmOverloads constructor(
        var vb: ActivityBaseWebUrlBinding
    ) : WebChromeClient() {


        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            if (!title.isNullOrEmpty()) {
                vb?.titleBar?.centerTextView?.text = title
            }

        }
    }


}